// pages/index/task_detail.js
//获取应用实例
var msg = require("../../../siteinfo.js");
const app = getApp()
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const innerAudioContext_retrun = wx.createInnerAudioContext()
const innerAudioContext_con = wx.createInnerAudioContext()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSpeaking: false,
    index: 0,
    recive: "",
    answerState: 0,
    status: false,
    already: false,
    return_answer: false,
    my_answer: false,
    hide: false,
    start_btn: true,
    btn_show: true,
    audio_play: false,
    audio_pause: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    console.log(options)
    //用户的id
    var userid = options.userid;
    console.log(userid)
    //当前点击的下标
    // var index = options.index;
    var index = that.data.index
    // var state = options.state;
    // console.log(state)
    var status_s = options.status
    that.setData({
      userid: userid,
      index: index,
      answer_index: Number(index) + 1,
      status_s: status_s
    })

    // —————————————— 获取网址——————————
    app.util.request({
      "url": "entry/wxapp/Attachurl",
      'cachetime': '0',
      success: function(res) {
        that.setData({
          url: res.data
        })
      }
    })

    //从缓存里面取出所有列表的数据
    var all = wx.getStorageSync('all_list')
    //console.log(all)
    that.setData({
      all: all,
    })
    that.detail()
  },

  // 播放音频
  audio: function (e) {
    var that = this
    var a = that.data
    var audio_play = a.audio_play
    var audio_pause = a.audio_pause
    if (audio_play == false) {
      that.audioCtx.play()
      that.setData({
        audio_play: true
      })
    } else {
      that.audioCtx.pause()
      that.setData({
        audio_play: false,
      })
    }
  },
  //列表详情
  detail: function(e) {
    var that = this;
    // console.log(that)
    //var all = that.data.all
    var index = that.data.index
    //var task_id = all[index].id
    var userid = that.data.userid
    var status_s = that.data.status_s
    console.log(status_s)
    console.log(userid)
    app.util.request({
      "url": "entry/wxapp/Answers",
      'cachetime': '0',
      data: {
        userid: userid,
        status: status_s
      },
      success: function(res) {
        console.log(res)
        if (res.data.code == 200) {
          that.setData({
            task: res.data.list[index],
            all_length: res.data.list.length
          })
        }
        that.setData({
          none: res.data
        })
      }
    })
  },

  /*点击下一题 */
  onNext: function(e) {
    var that = this
    var index = that.data.index
    var answer_index = that.data.answer_index
    var state = that.data.status
    console.log(state)
    if (state == true) {
      that.setData({
        already_answer: true,
        status: false,
        my_answer: false,
        btn_show: true,
      })
      // if (1 == that.data.all_length) {
      //   wx.showModal({
      //     title: '提示',
      //     content: '已经到该学生最后一题了',
      //     success: function(res) {
      //       if (res.confirm) {
      //         console.log('用户点击确定')
      //         wx.navigateBack({
      //           delta: 1
      //         })
      //       } else if (res.cancel) {
      //         console.log('用户点击取消')

      //       }
      //     }
      //   })
      // } else {
       
      // }
      that.subReply()
    } else {
      wx.showModal({
        title: '提示',
        content: '只有批改了这一题,才能进入下一题',
        success: function(res) {
          console.log(res)
          if (res.confirm) {
            //确认则打开设置页面
          }
        }
      })
    }
  },

  // /*点击上一题 */
  // onprev: function (e) {
  //   var that=this;
  //   var index=that.data.index;
  //   var answer_index=that.data.answer_index;
  //   if (answer_index==1){
  //     wx.showModal({
  //       title: '',
  //       content: '已经到第一题了',
  //     })      
  //   }else{
  //     that.setData({
  //       index: Number(that.data.index) - 1,
  //       answer_index: Number(that.data.answer_index) - 1,
  //     })
  //     that.detail()
  //   }
  // },

  //开始录音的时候
  handleTouchStart: function(e) {
    console.log(e)
    var that = this
    innerAudioContext_con.pause();
    innerAudioContext_con.onStop(() => {
      console.log('录音播放停止');
    })
    this.videoContext.pause()
    innerAudioContext.pause();
    innerAudioContext.onStop(() => {
      console.log('录音播放停止');
    })
    that.setData({
      hide: true,
      already: false,
      start_btn: false,
    })
    //判断是否授权
    wx.getSetting({
      success(res) {
        console.log(res)
        if (!res.authSetting['scope.record']) {
          console.log("没有授权z偶")
          that.setData({
              isSpeaking: false,
            }),
            wx.authorize({
              scope: 'scope.record',
              success() {
                console.log("授权成功")
                that.vioce()
              },
              fail() {
                console.log("拒接授权");
                wx.showModal({
                  title: '提示',
                  content: '您未授权录音,不能录音',
                  success: function(res) {
                    console.log(res)
                    if (res.confirm) {
                      //确认则打开设置页面
                      wx: wx.openSetting({
                        success: function(res) {
                          console.log(res)
                        },
                        fail: function(res) {
                          console.log(res)
                        },
                        complete: function(res) {},
                      })
                    }
                    else {
                      console.log("取消则返回上一页")
                      //取消则返回上一页
                      wx.navigateBack({
                        delta: 1
                      })
                    }
                  },
                })
              }
            })
        } else {
          that.vioce()
        }
      },
      fail: function(res) {
        console.log(res)
      }
    })
  },

  //获取录音
  vioce: function(e) {
    var that = this;
    //当前题目的id
    // var current_id = that.data.task.id
    // console.log("当前题目的id:" + current_id)
    var myDates = new Date()
    var start_min = myDates.getMinutes(); //获取当前分钟数(0-59)
    var start_miao = myDates.getSeconds(); //获取当前秒数(0-59)
    var start_time = start_min * 60 + start_miao
    // console.log("分钟:" + start_min + "" + "秒:" + start_miao)
    // console.log(start_time)
    // console.log(that)
    //显示话筒
    that.setData({
      isSpeaking: true,
      start_time: start_time
    })

    const options = {
      duration: 60000, //指定录音的时长，单位 ms
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 500, //指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart((res) => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError(res => {
      console.log(res);
    })
  },

  //停止录音
  handleTouchEnd: function(e) {
    var that = this;
    console.log(that)
    //当前题目的id
    var current_id = that.data.task.id
    console.log("当前题目的id:" + current_id)
    var user_id = wx.getStorageSync('user_msg').id
    console.log(user_id)

    var start_times = that.data.start_time;
    var myDate = new Date()
    var end_min = myDate.getMinutes(); //获取当前分钟数(0-59)
    var end_miao = myDate.getSeconds(); //获取当前秒数(0-59)
    // console.log("分钟:" + end_min + "" + "秒:" + end_miao)
    var end_time = end_min * 60 + end_miao
    var min_time = end_time - start_times
    // console.log(end_time)
    //隐藏话筒
    that.setData({
        isSpeaking: false,
        min_time: min_time,
        my_answer: true,
        hide: false,
        start_btn: true,
      }),

      recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      // console.log('停止录音', res.tempFilePath)
      const {
        tempFilePath
      } = res
      var data = res.tempFilePath
      console.log(res.tempFilePath)
      that.setData({
        my_audio: res.tempFilePath
      })
      wx.uploadFile({
        url: msg.siteroot + '?i=' + msg.uniacid + '&c=entry&a=wxapp&do=UploadFiles&m=zh_jypx',
        filePath: res.tempFilePath,
        name: 'upfile',
        formData: {},
        success: function(res) {
          var recive = res.data
          console.log(res)
          that.setData({
            recive: res.data
          })
        }
      })
    })
  },

  //点击正确
  onTrue: function(e) {
    var that = this;
    var true_id = e.currentTarget.dataset.id
    var answer_id = e.currentTarget.dataset.answer_id
    //回复内容
    var recive_con = that.data.recive
    console.log(recive_con)
    var index = that.data.index
    var t_id = that.data.task.id
    var userid = that.data.task.users_id
    console.log(t_id)
    //console.log(true_id)
    //console.log(answer_id)
    wx.showModal({
      title: '提示',
      content: '确定答案正确吗?',
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.setData({
            answer_id: answer_id,
            error_id: true_id
          })
          // app.util.request({
          //   "url": "entry/wxapp/CorrectTask",
          //   'cachetime': '0',
          //   data: {
          //     status: true_id,
          //     answer_id: answer_id,
          //     task_id: t_id,
          //     recive_con: recive_con,
          //     userid: userid,
          //   },
          //   success: function (res) {
          //     console.log(res)
          //     that.setData({
          //       status:true,
          //       btn_show: false
          //     })
          //     wx.showToast({
          //       title: '批改成功',
          //       icon: 'none',
          //       duration: 1000
          //     })
          //   }
          // })
          that.setData({
            status: true,
            btn_show: false
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // =========================================提交回复内容===============================================
  subReply: function(e) {
    var that = this
    console.log(that.data)
    var userid = that.data.task.users_id
    var t_id = that.data.task.id
    var answer_id = that.data.answer_id
    var error_id = that.data.error_id
    var recive_con = that.data.recive
    console.log('用户的id为' + userid)
    console.log('题目的id为' + t_id)
    console.log('不知道是啥，注释都不写,看个鬼' + answer_id)
    console.log('回复的内容' + recive_con)
    console.log('状态码' + error_id)
    app.util.request({
      "url": "entry/wxapp/CorrectTask",
      'cachetime': '0',
      data: {
        status: error_id, //正确错误状态
        answer_id: answer_id, //
        task_id: t_id, //题目的id
        recive_con: recive_con, //回复内容
        userid: userid, //做题人的id
        t_answer_time:that.data.min_time
      },
      success: function(res) {
        console.log(res)
        wx.showToast({
          title: '批改成功',
          icon: 'none',
          duration: 1000
        })
        if (that.data.all_length != 1) {
          setTimeout(function () {
            that.setData({
              answer_index: Number(that.data.answer_index) + 1,
              recive: ''
            })
            that.detail()
          }, 1000)
        } else {
          wx.showModal({
            title: '',
            content: '批改完毕',
            success:res=>{
              wx.navigateBack({
                delta:1
              })
            }
          })
        }
        


      }
    })
  },
  //点击错误
  onError: function(e) {
    var that = this;
    var error_id = e.currentTarget.dataset.id
    console.log('这是错误的状态码' + error_id)
    var answer_id = e.currentTarget.dataset.answer_id
    var userid = that.data.task.users_id
    var index = that.data.index
    //回复内容
    var recive_con = that.data.recive
    console.log(recive_con)
    var t_id = that.data.task.id
    console.log(t_id)
    wx.showModal({
      title: '提示',
      content: '确定答案错误吗?',
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.setData({
            answer_id: answer_id,
            error_id: error_id
          })
          that.setData({
            status: true,
            btn_show: false
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //播放回答内容
  audioPlay: function() {
    var that = this;
    var task_list = that.data.task
    var my_audio = task_list.answer
    var url = that.data.url
    var all_url = url + my_audio
    //console.log(all_url)
    innerAudioContext.src = all_url;
    var already = that.data.already
    console.log(already)

    //暂停视频播放
    innerAudioContext_con.pause();
    innerAudioContext_con.onStop(() => {})
    //暂停视频播放
    this.videoContext.pause()

    if (already == false) {
      innerAudioContext.play();
      innerAudioContext.onPlay(() => {
        console.log('录音播放中');
      })
      console.log('语音播放事件')
      //暂停老师回复
      innerAudioContext_retrun.pause()
      innerAudioContext_retrun.onStop(() => {
        console.log('录音播放停止');
      })
      that.setData({
        already: true,
        return_answer: false,
        hide: true,
      })
    } else {
      innerAudioContext.pause();
      innerAudioContext.onStop(() => {
        console.log('录音播放停止');
      })
      wx.pauseVoice()
      console.log('语音暂停事件')
      that.setData({
        already: false,
        hide: false,
      })
    }

    innerAudioContext.onEnded(() => {
      console.log('录音播放结束');
      that.setData({
        already: false,
        hide: false,
      })
    })

  },

  //播放老师回复
  recive_answer: function() {
    var that = this;
    var my_audio = that.data.my_audio
    console.log(that)
    innerAudioContext_retrun.src = my_audio;

    //暂停视频播放
    innerAudioContext_con.pause();
    innerAudioContext_con.onStop(() => {})
    this.videoContext.pause()
    var return_answer = that.data.return_answer
    console.log(return_answer)
    if (return_answer == false) {
      innerAudioContext_retrun.play();
      innerAudioContext_retrun.onPlay(() => {
        console.log('录音播放中');
      })
      //暂停回答内容
      innerAudioContext.pause();
      innerAudioContext.onStop(() => {
        console.log('录音播放停止');
      })
      that.setData({
        return_answer: true,
        already: false,
        hide: true,
      })
    } else {
      innerAudioContext_retrun.pause();
      innerAudioContext_retrun.onStop(() => {
        console.log('录音播放停止');
      })
      that.setData({
        return_answer: false,
        hide: false,
      })
    }

    innerAudioContext_retrun.onEnded(() => {
      console.log('录音播放结束');
      that.setData({
        return_answer: false,
        hide: false,
      })
    })
  },

  // //播放音频
  // audio: function() {
  //   var that = this;
  //   console.log(that)
  //   var l_audio = that.data.task.voice;
  //   console.log(that.data.task.voice)
  //   innerAudioContext_con.autoplay = false;
  //   innerAudioContext_con.src = l_audio;
  //   //暂停视频
  //   this.videoContext.pause()

  //   innerAudioContext_con.play();
  //   innerAudioContext_con.onPlay(() => {})
  //   innerAudioContext_con.onError((res) => {
  //     console.log(res.errMsg)
  //     console.log(res.errCode)
  //   })

  // },
  //播放视频
  video: function() {
    this.videoContext.play()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.videoContext = wx.createVideoContext("videoId")
    this.audioCtx = wx.createAudioContext('myAudios')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})